#!/bin/bash

DEFAULT_TIMEZONE=Asia/Shanghai

help() {
  echo "Usage:"
  echo "  zmicro config timezone [TIMEZONE]"
  echo ""
  echo "    Default timezone: Asia/Shanghai"
}

is_timezone_seted() {
  local tz=$1
  if [ -z $tz ]; then
    log::error "[is_timezone_seted] timezone is required"
    exit 1
  fi

  # @1 TZ env
  if [ -n "$TZ" ]; then
    echo "true"
    return
  fi

  # @2 /etc/timezone
  if [ -f "/etc/timezone" ]; then
    cat /etc/timezone | grep $tz >> /dev/null 2>&1
    if [ "$?" = "0" ]; then
      echo "true"
      return
    fi
  fi

  # @3 timedatectl
  which timedatectl >> /dev/null 2>&1
  if [ "$?" = "0" ]; then
    sudo timedatectl show | grep $tz >> /dev/null 2>&1
    if [ "$?" = "0" ]; then
      echo "true"
      return
    fi
  fi

  echo "false"
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  local _timezone=$1
  local timezone=${_timezone:-$DEFAULT_TIMEZONE}
  log::debug "timezone: $timezone"

  # Show current timezone
  # timedatectl status

  # List all available timezones
  # timedatectl list-timezones

  # Set timezone
  if [ "$(os::is_docker)" = "true" ]; then
    # @TODO
    # date >> /dev/null 2>&1
    log::warn "[$(timestamp)][config] @TODO set timezone in docker"
    return 
  fi

  if [ "$(is_timezone_seted $timezone)" = "true" ]; then
    return
  fi

  sudo timedatectl set-timezone $timezone
  if [ "$?" != "0" ]; then
    log::error "[$(timestamp)][config] Failed to set timezone: $timezone"
  else
    log::success "[$(timestamp)][config] Current timezone: $timezone"
  fi
}

run() {
  core $@
}

run $@
